Scala Exceptions

An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time. These events change the flow control of the program in execution. These are situations that are not too dangerous and can be handled by the program. Exception handling is a mechanism which is used to handle abnormal conditions. You can also avoid termination of your program unexpectedly.

Exception Hierarchy
All exception and errors types are sub classes of class Throwable, which is base class of hierarchy. One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch. NullPointerException is an example of such an exception. Another branch, Error are used by the Java run-time system(JVM) to indicate errors having to do with the run-time environment itself(JRE). StackOverflowError is an example of such an error.

Exception handling in Scala is implemented differently, but it behaves exactly like Java and works seamlessly with existing Java libraries. In scala, All exceptions are unchecked. there is no concept of checked exception Scala facilitates a great deal of flexibility in terms of the ability to choose whether to catch an exception.
Note: At compile time “checked” exceptions are checked In Java . If a method might throw an IOException, we must declare it.

How does Scala Exception Work?
Exceptions in scala work the same way as in C++ or Java. When an exception occurs, say an ArithmeticException as shown in the previous example the current operation is aborted, and the runtime system looks for an exception handler that can accept an ArithmeticException. Control resumes with the innermost such handler. If no such handler exists, the program terminates.

Scala Program Example without Exception Handling
class ExceptionExample{
def divide(a:Int, b:Int) = {
a/b // Exception occurred here
println("Rest of the code is executing...")
}
}
object Demo{
def main(args:Array[String]){
var e = new ExceptionExample()
e.divide(100,0)
}
}
Output:

java.lang.ArithmeticException: / by zero

Scala Try Catch
Scala provides try and catch block to handle exception. The try block is used to enclose suspect code. The catch block is used to handle exception occurred in try block. You can have any number of try catch block in your program according to need.

Scala Try Catch Example
In the following program, we have enclosed our suspect code inside try block. After try block we have used a catch handler to catch exception. If any exception occurs, catch handler will handle it and program will not terminate abnormally.
class ExceptionExample{
def divide(a:Int, b:Int) = {
try{
a/b
}catch{
case e: ArithmeticException => println(e)
}
println("Rest of the code is executing...")
}
}
object Demo{
def main(args:Array[String]){
var e = new ExceptionExample()
e.divide(100,0)
}
}

Output:
java.lang.ArithmeticException: / by zero
Rest of the code is executing...

Example 2
In this example, we have two cases in our catch handler. First case will handle only arithmetic type exception. Second case has Throwable class which is a super class in exception hierarchy. The second case is able to handle any type of exception in your program. Sometimes when you don't know about the type of exception, you can use super class.

    class ExceptionExample{ 
        def divide(a:Int, b:Int) = { 
            try{ 
                a/b 
                var arr = Array(1,2) 
                arr(10) 
            }catch{ 
                case e: ArithmeticException => println(e) 
                case ex: Throwable =>println("found a unknown exception"+ ex) 
            } 
            println("Rest of the code is executing...") 
        } 
    } 
    object MainObject{ 
        def main(args:Array[String]){ 
            var e = new ExceptionExample() 
            e.divide(100,10) 
      
        } 
    } 

Output:
found a unknown exceptionjava.lang.ArrayIndexOutOfBoundsException: 10
Rest of the code is executing...

The finally block is used to release resources during exception. Resources may be file, network connection, database connection etc. the finally block executes guaranteed. The following program illustrate the use of finally block.

    class ExceptionExample{ 
        def divide(a:Int, b:Int) = { 
            try{ 
                a/b 
                var arr = Array(1,2) 
                arr(10) 
            }catch{ 
                case e: ArithmeticException => println(e) 
                case ex: Exception =>println(ex) 
                case th: Throwable=>println("found a unknown exception"+th) 
            } 
            finally{ 
                println("Finaly block always executes") 
            } 
            println("Rest of the code is executing...") 
        } 
    } 
       object MainObject{ 
        def main(args:Array[String]){ 
            var e = new ExceptionExample() 
            e.divide(100,10) 
      
        } 
    } 

Output:
java.lang.ArrayIndexOutOfBoundsException: 10
Finally block always executes
Rest of the code is executing...

Scala Throw keyword
You can throw exception explicitly in you code. Scala provides throw keyword to throw exception. The throw keyword mainly used to throw custom exception. An example is given below of using scala throw exception keyword.
Scala Throw Example

    class ExceptionExample2{ 
        def validate(age:Int)={ 
            if(age<18) 
                throw new ArithmeticException("You are not eligible") 
            else println("You are eligible") 
        } 
    }  
    object MainObject{ 
        def main(args:Array[String]){ 
            var e = new ExceptionExample2() 
            e.validate(10) 
          } 
    } 

Output:
java.lang.ArithmeticException: You are not eligible

Scala Throws Keyword
Scala provides throws keyword to declare exception. You can declare exception with method definition. It provides information to the caller function that this method may throw this exception. It helps to caller function to handle and enclose that code in try-catch block to avoid abnormal termination of program. In scala, you can either use throws keyword or throws annotation to declare exception.
Scala Throws Example

    class ExceptionExample4{ 
        @throws(classOf[NumberFormatException]) 
        def validate()={ 
            "abc".toInt 
        } 
    } 
     
    object MainObject{ 
        def main(args:Array[String]){ 
            var e = new ExceptionExample4() 
            try{ 
                e.validate() 
            }catch{ 
                case ex : NumberFormatException => println("Exception handeled here") 
            } 
            println("Rest of the code executing...") 
        } 
    } 

Output:

Exception handeled here
Rest of the code executing...

Scala Custom Exception
In scala, you can create your own exception. It is also known as custom exceptions. You must extend Exception class while declaring custom exception class. You can create your own exception message in custom class. Let's see an example.
Scala Custom Exception Example

    class InvalidAgeException(s:String) extends Exception(s){} 
    class ExceptionExample{ 
        @throws(classOf[InvalidAgeException]) 
        def validate(age:Int){ 
            if(age<18){ 
                throw new InvalidAgeException("Not eligible") 
            }else{ 
                println("You are eligible") 
            } 
        } 
    } 
    object MainObject{ 
        def main(args:Array[String]){ 
            var e = new ExceptionExample() 
            try{ 
                e.validate(5) 
            }catch{ 
                case e : Exception => println("Exception Occured : "+e) 
            } 
        } 
    } 
Output:
Exception Occured : InvalidAgeException: Not eligible

No comments:

Post a Comment